﻿﻿// 引入页面助手工具和云助手工具
const pageHelper = require('../../../config/project_helpers_config').pageHelper;
const cloudHelper = require('../../../config/project_helpers_config').cloudHelper;
// 从业务配置引入ProjectDataBiz
const { ProjectDataBiz } = require('../../../config/biz_config');
// 引入MobX绑定工具和Store
const { createStoreBindings } = require('../../../config/libs_config').mobxMiniprogramBindings;
// 从统一Store配置引入项目Store
const { projectStore, researchStore } = require('../../../config/store_config');
// 引入领域模型
const { ProjectModel } = require('../../../config/models_config');
// 引入工具库
const { dayjs } = require('../../../config/libs_config');
// 引入缓存助手
const { cacheHelper, dateHelper, statusHelper } = require('../../../config/project_helpers_config');
// 表单配置相关引用统一如下：
const { getFormConfigByType } = require('../../../comm/biz/project_data_biz.js');
const { logEvent } = require('../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../helpers/network_helper.js');

// 获取同一位置的配置Store
const storeConfig = require('../../../config/store_config');
// 提前创建备用的空方法
const emptyFn = async () => ({});

Page({
  data: {
    project: null,
    formData: {},
    formError: {},
    typeOptions: [
      { text: '电机控制类', value: '霍尔', checked: true },
      { text: '位置传感类', value: '磁编', checked: false },
      { text: '工控类', value: '工控', checked: false }
    ],
    priorityOptions: [
      { text: '低', value: 'low', checked: false },
      { text: '中', value: 'normal', checked: true },
      { text: '高', value: 'high', checked: false },
      { text: '紧急', value: 'urgent', checked: false }
    ],
    isSubmitting: false, // 是否正在提交中
    projectTypes: ['磁编', '霍尔', '吸尘器', '风机', '水泵', '其他'], // 项目类型选项
    projectTypeNames: {
      '磁编': '电机控制类',
      '霍尔': '电机控制类',
      '风机': '电机控制类',
      '水泵': '电机控制类',
      '吸尘器': '其他类型',
      '其他': '其他类型'
    },
    projectTypeIndex: 1,
    departments: ['研发部', '产品部', '设计部', '运营部', '市场部'],
    departmentIndex: -1,
    leaders: [
      { id: 1, name: '张工' },
      { id: 2, name: '李工' },
      { id: 3, name: '王工' },
      { id: 4, name: '赵工' }
    ],
    leaderIndex: -1,
    // 添加销售人员数据
    salespeople: [
      { id: 101, name: '张销售' },
      { id: 102, name: '李销售' },
      { id: 103, name: '王销售' },
      { id: 104, name: '赵销售' }
    ],
    salespersonIndex: -1,
    // 添加控制方式选项数组
    controlModes: ['恒功率', '恒转速'], // 修改控制模式选项
    controlInterfaces: ['按键控制', 'PWM控制', 'CLOCK控制', 'VSP控制', 'IIC协议控制', 'UART控制', 'SPI控制'],
    controlAlgorithms: ['FOC', '方波', '开环', '其他'], // 添加控制算法选项数组
    rotationOptions: ['无', '运行中正反转', '停止正反转'], // 修改正反转选项数组
    // 添加保护选项数组
    protectionOptions: ['无', '有，自恢复', '有，手动重开', '有，有，仅断电重启'],
    // 限流保护选项（简化为"有"、"无"）
    currentLimitOptions: ['无', '有'],
    // 表单配置
    formConfig: null,
    // 添加验证错误信息
    validationErrors: {},
    // 附件列表
    attachments: []
  },

  /**
   * 自定义分享
   */
  onShareAppMessage: function(res) {
    // 获取当前页面路径
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const url = '/' + currentPage.route;
    
    return {
      title: '邀请您填写项目信息',
      path: url + '?share=1',  // 通过参数标记这是分享打开的
      imageUrl: '/projects/oa/images/project/share_project.png',  // 更新为正确路径
      success: function(res) {
        // 分享成功回调
        wx.showToast({
          title: '分享成功',
          icon: 'success'
        });
      },
      fail: function(res) {
        // 分享失败回调
        console.log('分享失败', res);
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_project_edit' });
    
    try {
      // 检查projectStore是否包含必要的方法
      console.log('projectStore 状态:', {
        hasStore: !!projectStore,
        hasClearProject: typeof projectStore.clearProject === 'function',
        hasLoadProjectList: typeof projectStore.loadProjectList === 'function',
        hasLoadProjectDetail: typeof projectStore.loadProjectDetail === 'function'
      });
      
      // 使用storeConfig中的项目Store或fallback到空实现
      const safeProjectStore = projectStore || storeConfig.fallbackStore || {};
      
      // 创建MobX绑定，确保方法存在（如果不存在则使用空方法）
      this.storeBindings = createStoreBindings(this, {
        store: safeProjectStore,
        fields: ['projectList', 'currentProject'],
        actions: {
          loadProjectList: typeof safeProjectStore.loadProjectList === 'function' ? 'loadProjectList' : null,
          loadProjectDetail: typeof safeProjectStore.loadProjectDetail === 'function' ? 'loadProjectDetail' : null,
          clearProject: typeof safeProjectStore.clearProject === 'function' ? 'clearProject' : null
        }
      });
      
      this._loadOptions = options;
      
      // 设置今天的日期和默认截止日期
      const today = dayjs().format('YYYY-MM-DD');
      const defaultDeadline = this._getDefaultDeadline();
      
      if (options.id) {
        // 编辑模式
        this.getProjectDetail(options.id);
      } else {
        // 生成更具体的随机型号
        const randomCode = Math.floor(Math.random() * 9000 + 1000);
        const modelCode = `ABS-H${randomCode}`;
        
        // 新建模式，使用默认项目模型
        const defaultProject = {
          projectType: '霍尔',
          projectTypeName: '电机控制类',
          model: modelCode,
          customerName: 'ABS',
          startDate: today,
          deadline: defaultDeadline,
          priority: 'normal',
          workTemp: '0~70',
          certification: 'CE/ROHS',
          conformalCoating: '无',
          controlMode: '恒功率',
          controlInterface: '按键控制',
          controlAlgorithm: 'FOC',
          rotation: '无',
          protection: '无',
          hasHall: '无',
          hasFG: '无',
          lowPower: '0',
          startupTime: '1',
          ratedVoltage: '10.8',
          maxPower: '120',
          maxSpeed: '110000',
          polePairs: '1',
          hasBrake: '无',
          // 保护相关默认值
          stallProtection: '有，自恢复',
          stallHoldTime: '1',
          stallRestartTime: '1',
          stallRestartCount: '1',
          overvoltageProtection: '有，自恢复',
          overvoltageValue: '15',
          overvoltageRecoveryValue: '14',
          undervoltageProtection: '有，自恢复',
          undervoltageValue: '6',
          undervoltageRecoveryValue: '6.5',
          temperatureProtection: '有，自恢复',
          protectionTemp: '90',
          recoveryTemp: '80',
          overcurrentProtection: '有，自恢复',
          overcurrentValue: '30',
          currentLimitProtection: '有',
          currentLimitValue: '12',
          blockageProtection: '有，自恢复',
          blockageDiameter: '3',
          blockageHoldTime: '5',
          phaseProtection: '有，自恢复',
          department: '待定',
          projectLeadId: null,
          projectLead: '待定',
          salespersonId: null,
          salespersonName: '待定',
          hasSample: '无'
          // 其他默认值...
        };
      
        this.setData({
          project: defaultProject,
          formData: this._projectToFormData(defaultProject)
        });
        
        // 初始化表单配置
        this.initFormConfig(defaultProject.projectType);
      }
    } catch (err) {
      console.error('[项目编辑] onLoad 错误:', err);
      pageHelper.showErrToast('页面加载失败');
    }
  },
  
  /**
   * 获取默认截止日期（当前日期加3个月）
   */
  _getDefaultDeadline() {
    const date = dayjs();
    return date.add(3, 'month').format('YYYY-MM-DD');
  },
  
  /**
   * 监听MobX数据变化，更新页面数据
   */
  onStoreChange: function() {
    if (this.data.currentProject) {
      this.updatePageWithProjectData(this.data.currentProject);
    }
    
    // 处理错误信息
    if (this.data.error) {
      pageHelper.showErrToast(this.data.error);
    }
    
    // 处理加载状态
    this.setData({
      isSubmitting: this.data.loading
    });
  },
  
  /**
   * 根据MobX中的项目数据更新页面
   */
  updatePageWithProjectData: function(projectData) {
    if (!projectData) return;
    
    // 更新项目数据，保持原有字段结构
    this.setData({
      project: {
        ...this.data.project,
        ...projectData
      },
      formData: this._projectToFormData(projectData)
    });
    
    // 更新应用类型索引
    if (projectData.projectType) {
      const index = this.data.projectTypes.findIndex(
        type => type === projectData.projectType
      );
      this.setData({
        projectTypeIndex: index >= 0 ? index : -1
      });
    }
    
    // 更新部门索引
    if (projectData.department) {
      const departmentIndex = this.data.departments.findIndex(
        dept => dept === projectData.department
      );
      this.setData({
        departmentIndex: departmentIndex >= 0 ? departmentIndex : -1
      });
    }
    
    // 更新负责人索引
    if (projectData.projectLeadId) {
      const leaderIndex = this.data.leaders.findIndex(
        leader => leader.id === projectData.projectLeadId
      );
      this.setData({
        leaderIndex: leaderIndex >= 0 ? leaderIndex : -1
      });
    }
    
    // 更新销售人员索引
    if (projectData.salespersonId) {
      const salespersonIndex = this.data.salespeople.findIndex(
        salesperson => salesperson.id === projectData.salespersonId
      );
      this.setData({
        salespersonIndex: salespersonIndex >= 0 ? salespersonIndex : -1
      });
    }
    
    // 初始化表单配置
    this.initFormConfig(projectData.projectType);
  },
  
  /**
   * 初始化表单配置（保持原有逻辑）
   */
  initFormConfig: function(projectType) {
    // 根据项目类型设置不同的表单配置
    const formConfig = getFormConfigByType(projectType);
    this.setData({
      formConfig
    });
  },
  
  /**
   * 项目数据转表单数据
   */
  _projectToFormData(project) {
    if (!project) return {};
    
    // 处理日期格式 - 使用dayjs将时间戳或日期字符串转为YYYY-MM-DD格式
    let startDate = '';
    let deadline = '';
    
    // 处理开始日期
    if (project.startDate) {
      // 如果已经是日期字符串格式，直接使用
      if (typeof project.startDate === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(project.startDate)) {
        startDate = project.startDate;
      } else {
        // 否则尝试用dayjs转换
        startDate = dayjs(project.startDate).format('YYYY-MM-DD');
      }
    } else {
      startDate = dayjs().format('YYYY-MM-DD');
    }
    
    // 处理截止日期
    if (project.deadline) {
      // 如果已经是日期字符串格式，直接使用
      if (typeof project.deadline === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(project.deadline)) {
        deadline = project.deadline;
      } else {
        // 否则尝试用dayjs转换
        deadline = dayjs(project.deadline).format('YYYY-MM-DD');
      }
    } else {
      deadline = this._getDefaultDeadline();
    }
    
    return {
      customerName: project.customerName || 'ABS',
      model: project.model || 'ABS-',
      projectType: project.projectType || '霍尔',
      projectTypeName: project.projectTypeName || '电机控制类',
      startDate: startDate,
      deadline: deadline,
      priority: project.priority || 'normal',
      description: project.description || '',
      workTemp: project.workTemp || '0~70',
      certification: project.certification || 'CE/ROHS',
      lowPower: project.lowPower || '0',
      startupTime: project.startupTime || '1',
      conformalCoating: project.conformalCoating || '无',
      ratedVoltage: project.ratedVoltage || '10.8',
      maxPower: project.maxPower || '120',
      maxSpeed: project.maxSpeed || '110000',
      polePairs: project.polePairs || '1',
      hasHall: project.hasHall || '无',
      hasFG: project.hasFG || '无',
      hasBrake: project.hasBrake || '无',
      controlMode: project.controlMode || '恒功率',
      controlAlgorithm: project.controlAlgorithm || 'FOC',
      rotation: project.rotation || '无',
      controlInterface: project.controlInterface || '按键控制',
      hasSample: project.hasSample || '无',
      sampleCount: project.sampleCount || '0',
      sampleImages: project.sampleImages || [],
      department: project.department || '',
      projectLeadId: project.projectLeadId || null,
      projectLead: project.projectLead || '',
      salespersonId: project.salespersonId || null,
      salespersonName: project.salespersonName || '',
      // 各种保护参数
      stallProtection: project.stallProtection || '有，自恢复',
      overvoltageProtection: project.overvoltageProtection || '有，自恢复',
      undervoltageProtection: project.undervoltageProtection || '有，自恢复',
      temperatureProtection: project.temperatureProtection || '有，自恢复',
      overcurrentProtection: project.overcurrentProtection || '有，自恢复',
      currentLimitProtection: project.currentLimitProtection || '有',
      blockageProtection: project.blockageProtection || '有，自恢复',
      phaseProtection: project.phaseProtection || '有，自恢复',
      
      // 保护子项参数
      stallHoldTime: project.stallHoldTime || '1',
      stallRestartTime: project.stallRestartTime || '1',
      stallRestartCount: project.stallRestartCount || '1',
      overvoltageValue: project.overvoltageValue || '15',
      overvoltageRecoveryValue: project.overvoltageRecoveryValue || '14',
      undervoltageValue: project.undervoltageValue || '6',
      undervoltageRecoveryValue: project.undervoltageRecoveryValue || '6.5',
      protectionTemp: project.protectionTemp || '90',
      recoveryTemp: project.recoveryTemp || '80',
      overcurrentValue: project.overcurrentValue || '30',
      currentLimitValue: project.currentLimitValue || '12',
      blockageDiameter: project.blockageDiameter || '3',
      blockageHoldTime: project.blockageHoldTime || '5',
      
      // PWM控制参数
      pwmStartDuty: project.pwmStartDuty || '10',
      pwmStopDuty: project.pwmStopDuty || '8',
      pwmDutyRange: project.pwmDutyRange || '10～90',
      pwmFreqRange: project.pwmFreqRange || '1～10',
      
      // VSP控制参数
      vspStartVoltage: project.vspStartVoltage || '1.0',
      vspStopVoltage: project.vspStopVoltage || '0.8',
      vspVoltageRange: project.vspVoltageRange || '1.0～4.5',
      
      // 附件
      attachments: project.attachments || [],
      
      // 控制详细描述
      controlDescription: project.controlDescription || '',
      
      // 添加项目状态
      status: project.status || 'planning',
      level1: project.level1 !== undefined ? project.level1 : 0,
      level2: project.level2 || 'director',
      statusDesc: project.statusDesc || '待部门主管审核',
      progress: project.progress !== undefined ? project.progress : 0
    };
  },
  
  /**
   * 转换表单数据为项目对象
   */
  _formDataToProject(formData) {
    console.log('[_formDataToProject] 开始转换表单数据为项目对象:', formData);
    
    // 检查是否特殊项目类型（只需基础字段）
    const isSpecialType = formData.projectType === '磁编' || formData.projectType === '霍尔';
    
    // 基础项目数据
    const baseProjectData = {
      model: formData.model,
      customerName: formData.customerName,
      startDate: formData.startDate,
      deadline: formData.deadline,
      priority: formData.priority || 'normal',
      projectType: formData.projectType,
      projectTypeName: this.data.projectTypeNames[formData.projectType] || '电机控制类',
      projectLead: formData.projectLead || '待定',
      projectLeadId: formData.projectLeadId || -1,
      sampleCount: formData.sampleCount || '0',
      hasSample: formData.hasSample || '无',
      sampleImages: this.data.project?.sampleImages || [],
      // 添加缺失的关键字段
      description: formData.description || '', // 添加项目描述
      salespersonId: formData.salespersonId || -1, // 添加销售ID
      salespersonName: formData.salespersonName || '待定', // 添加销售名称
      attachments: this.data.attachments || [], // 添加附件列表
      // 将部门提升为顶级字段
      department: formData.department || '待定',
      // extData字段保留有限必要的内容
      extData: {
        MODULE: 'plm',
        PID: 'plm',
        USE_PLM: true
      }
    };
    
    // 特殊类型只保留基础字段
    if (isSpecialType) return baseProjectData;

    // 常规类型合并产品参数
    const projectData = {
      ...baseProjectData,
      applicationType: formData.applicationType,
      workTemp: formData.workTemp,
      certification: formData.certification,
      lowPower: formData.lowPower,
      startupTime: formData.startupTime,
      conformalCoating: formData.conformalCoating,
      ratedVoltage: formData.ratedVoltage,
      maxPower: formData.maxPower,
      maxSpeed: formData.maxSpeed,
      polePairs: formData.polePairs,
      hasHall: formData.hasHall,
      hasFG: formData.hasFG,
      controlMode: formData.controlMode,
      controlAlgorithm: formData.controlAlgorithm,
      rotation: formData.rotation,
      hasBrake: formData.hasBrake,
      controlInterface: formData.controlInterface,
      // 添加控制详细描述字段
      controlDescription: formData.controlDescription || '',
      
      // 保护字段
      stallProtection: formData.stallProtection,
      overvoltageProtection: formData.overvoltageProtection,
      undervoltageProtection: formData.undervoltageProtection,
      temperatureProtection: formData.temperatureProtection,
      overcurrentProtection: formData.overcurrentProtection,
      currentLimitProtection: formData.currentLimitProtection,
      blockageProtection: formData.blockageProtection,
      // 添加缺相保护字段
      phaseProtection: formData.phaseProtection || '无',
    };
    
    // 添加保护子参数 - 堵转保护
    if (formData.stallProtection === '有，自恢复' || formData.stallProtection === '有，手动重开') {
      projectData.stallHoldTime = formData.stallHoldTime;
      
      if (formData.stallProtection === '有，自恢复') {
        projectData.stallRestartTime = formData.stallRestartTime;
        projectData.stallRestartCount = formData.stallRestartCount;
      }
    }
    
    // 添加保护子参数 - 过压保护
    if (formData.overvoltageProtection !== '无') {
      projectData.overvoltageValue = formData.overvoltageValue;
      
      if (formData.overvoltageProtection === '有，自恢复') {
        projectData.overvoltageRecoveryValue = formData.overvoltageRecoveryValue;
      }
    }
    
    // 添加保护子参数 - 欠压保护
    if (formData.undervoltageProtection !== '无') {
      projectData.undervoltageValue = formData.undervoltageValue;
      
      if (formData.undervoltageProtection === '有，自恢复') {
        projectData.undervoltageRecoveryValue = formData.undervoltageRecoveryValue;
      }
    }
    
    // 添加保护子参数 - 温度保护
    if (formData.temperatureProtection !== '无') {
      projectData.protectionTemp = formData.protectionTemp;
      
      if (formData.temperatureProtection === '有，自恢复') {
        projectData.recoveryTemp = formData.recoveryTemp;
      }
    }
    
    // 添加保护子参数 - 过流保护
    if (formData.overcurrentProtection !== '无') {
      projectData.overcurrentValue = formData.overcurrentValue;
    }
    
    // 添加保护子参数 - 电流限制保护
    if (formData.currentLimitProtection === '有') {
      projectData.currentLimitValue = formData.currentLimitValue;
    }
    
    // 添加保护子参数 - 堵塞保护
    if (formData.blockageProtection !== '无') {
      projectData.blockageDiameter = formData.blockageDiameter;
      projectData.blockageHoldTime = formData.blockageHoldTime;
    }
    
    // 控制接口子参数
    if (formData.controlInterface === 'PWM控制') {
      projectData.pwmStartDuty = formData.pwmStartDuty;
      projectData.pwmStopDuty = formData.pwmStopDuty;
      projectData.pwmDutyRange = formData.pwmDutyRange;
      projectData.pwmFreqRange = formData.pwmFreqRange;
    } else if (formData.controlInterface === 'VSP控制') {
      projectData.vspStartVoltage = formData.vspStartVoltage;
      projectData.vspStopVoltage = formData.vspStopVoltage;
      projectData.vspVoltageRange = formData.vspVoltageRange;
    }
    
    console.log('[_formDataToProject] 转换后的项目数据包含字段数:', Object.keys(projectData).length);
    return projectData;
  },
  
  /**
   * 验证表单数据
   */
  _validateForm(formData) {
    console.log('验证表单数据:', formData);
    console.log('当前项目类型:', formData.projectType);
    
    // 检查项目类型是否为数字索引，如果是则转换为字符串值
    if (typeof formData.projectType === 'number' || /^\d+$/.test(formData.projectType)) {
      const index = parseInt(formData.projectType);
      formData.projectType = this.data.projectTypes[index] || '风机';
      console.log('验证前项目类型索引转换为字符串:', formData.projectType);
    }
    
    const errors = {};
    
    // 基础字段验证逻辑(对所有项目类型都适用)
    if (!formData.model) {
      errors.model = '请输入项目型号';
    }
    
    if (!formData.customerName) {
      errors.customerName = '请输入客户名称';
    }
    
    if (!formData.startDate) {
      errors.startDate = '请选择开始日期';
    }
    
    if (!formData.deadline) {
      errors.deadline = '请选择截止日期';
    }
    
    // 验证项目负责人
    if (!formData.projectLead && !formData.projectLeadId) {
      errors.projectLead = '请选择项目负责人';
      console.log('项目负责人验证失败，当前值:', formData.projectLead);
    }
    
    // 验证销售人员
    if (!formData.salespersonName && !formData.salespersonId) {
      errors.salesperson = '请选择销售人员';
      console.log('销售人员验证失败，当前值:', formData.salespersonName);
    }
    
    return {
      valid: Object.keys(errors).length === 0,
      errors
    };
  },
  
  /**
   * 提交表单
   */
  submitForm(e) {
    let that = this;
    
    // 表单数据
    let formData = {};
    
    // 如果是通过按钮提交，则使用e.detail.value
    if (e && e.detail && e.detail.value) {
      formData = e.detail.value;
      console.log('[submitForm] 通过表单按钮提交，表单数据:', formData);
    }
    // 如果是通过API调用（如自定义按钮），则使用this.data.formData
    else {
      formData = this.data.formData;
      console.log('[submitForm] 通过API调用提交，表单数据:', formData);
    }
    
    // 防止重复提交
    if (this.data.isSubmitting) {
      console.log('[submitForm] 防止重复提交');
      pageHelper.showModal('操作进行中', '请勿重复提交，请稍候...');
      return;
    }
    
    this.setData({ isSubmitting: true });
    
    // 添加项目类型
    if (!formData.projectType) {
      formData.projectType = this.data.project.projectType;
      console.log('[submitForm] 添加项目类型:', formData.projectType);
    }
    
    // 添加优先级
    if (!formData.priority) {
      formData.priority = this.data.project.priority || 'normal';
      console.log('[submitForm] 添加优先级:', formData.priority);
    }
    
    // 添加状态字段
    formData.status = 'planning';  // 新建项目默认状态为"计划中"
    console.log('[submitForm] 添加状态字段:', formData.status);
    
    // 添加初始化必要字段
    formData.level1 = 0;  // 一级状态标识，0表示待审核
    formData.level2 = 'director';  // 二级状态标识，director表示流转到主管审核
    formData.statusDesc = '待部门主管审核';  // 状态描述
    formData.progress = 0;  // 项目进度，初始为0%
    console.log('[submitForm] 添加项目状态初始化字段');
    
    // 检查model字段是否具体有效
    if (!formData.model || formData.model === 'ABS-' || formData.model.length < 6) {
      // 生成随机字符作为型号后缀
      const randomCode = Math.floor(Math.random() * 9000 + 1000);
      formData.model = `ABS-H${randomCode}`;
      console.log('[submitForm] 优化项目型号:', formData.model);
    }
    
    // 表单校验
    const result = this._validateForm(formData);
    console.log('[submitForm] 表单验证结果:', result);
    
    if (!result.valid) {
      let errors = result.errors;
      let errArr = [];
      for (let k in errors) errArr.push(errors[k]);
      if (errArr.length > 0) {
        this.setData({ isSubmitting: false });
        return pageHelper.showModal('表单校验错误', errArr.join('\n'));
      }
    }
    
    // 缓存原始表单数据，以便需要重试时使用
    this._cachedFormData = formData;
    
    // 转换为项目数据
    let project = this._formDataToProject(formData);
    console.log('[submitForm] 转换后的项目数据:', project);
    
    // 强制设置项目模块标识
    project.MODULE = 'plm';  // 指定具体模块
    project.PID = 'plm';    // 确保PID正确
    project.USE_PLM = true;  // 添加标志指示使用PLM模块
    
    console.log('[submitForm] 发送请求前最终项目数据:', {
      PID: project.PID,
      MODULE: project.MODULE,
      route: 'research_project/create',
      model: project.model,
      projectType: project.projectType,
      status: project.status,
      level1: project.level1,
      level2: project.level2
    });
    
    // 执行提交操作
    this._executeSubmit(project);
  },
  
  /**
   * 执行提交操作（可重用于重试）
   * @param {Object} project 项目数据
   */
  _executeSubmit(project) {
    let that = this;
    
    // 提交前显示加载框
    wx.showLoading({
      title: '提交中',
      mask: true
    });
    
    // 强制设置PID参数，确保路由正确
    project.PID = 'plm';
    
    // 区分编辑和新增
    let callback = null;
    if (this.data.id) {
      // 更新项目
      callback = cloudHelper.callCloudData('research_project/update', project, {
        title: '更新中',
        mask: true,
        pid: 'plm'
      });
    } else {
      // 新增项目
      callback = cloudHelper.callCloudData('research_project/create', project, {
        title: '提交中',
        mask: true,
        pid: 'plm'
      });
    }
    
    callback.then(result => {
      wx.hideLoading();
      
      // 递归查找ID的辅助函数
      function findIdInObject(obj, maxDepth = 5, currentDepth = 0) {
        // 防止无限递归
        if (!obj || typeof obj !== 'object' || currentDepth > maxDepth) return null;
        
        // 直接检查是否是ID
        if (obj._id) return obj._id;
        if (obj.id) return obj.id;
        if (obj.projectId) return obj.projectId;
        
        // 递归检查子属性
        for (const key of Object.keys(obj)) {
          if (typeof obj[key] === 'object' && obj[key] !== null) {
            const foundId = findIdInObject(obj[key], maxDepth, currentDepth + 1);
            if (foundId) {
              console.log(`[submitForm] 在 ${key} 中找到ID: ${foundId}`);
              return foundId;
            }
          }
        }
        
        return null;
      }
      
      // 尝试处理result.result格式（某些API会在结果中嵌套一层result）
      const processedResult = result.result ? result.result : result;
      
      // 添加更详细的日志输出
      console.log('[submitForm] 提交成功，返回结果详情:', {
        result: processedResult,
        resultData: processedResult.data,
        resultId: processedResult.id,
        hasResultId: !!processedResult.id,
        hasResultDataId: processedResult.data && processedResult.data.id,
        resultDataType: processedResult.data ? typeof processedResult.data : 'undefined',
        resultKeys: Object.keys(processedResult || {}).join(','),
        resultDataKeys: processedResult.data ? Object.keys(processedResult.data).join(',') : 'none'
      });
      
      // 添加完整的返回数据日志，便于调试
      console.log('[submitForm] 完整返回结果:', JSON.stringify(processedResult));
      
      // 获取项目ID - 尝试多种可能的结构
      let id = null;
      
      // 方法1：直接从顶层获取
      if (processedResult && processedResult.id) {
        id = processedResult.id;
        console.log('[submitForm] 方法1成功获取ID:', id);
      } 
      // 方法2：从data对象获取id
      else if (processedResult && processedResult.data && processedResult.data.id) {
        id = processedResult.data.id;
        console.log('[submitForm] 方法2成功获取ID:', id);
      }
      // 方法3：从data对象获取_id（MongoDB常用格式）
      else if (processedResult && processedResult.data && processedResult.data._id) {
        id = processedResult.data._id;
        console.log('[submitForm] 方法3成功获取ID:', id);
      }
      // 方法3b：检查data.data嵌套结构（从日志发现的特殊情况）
      else if (processedResult && processedResult.data && processedResult.data.data) {
        if (processedResult.data.data._id) {
          id = processedResult.data.data._id;
          console.log('[submitForm] 方法3b成功从data.data._id获取ID:', id);
        } else if (processedResult.data.data.id) {
          id = processedResult.data.data.id;
          console.log('[submitForm] 方法3c成功从data.data.id获取ID:', id);
        }
      }
      // 方法4：如果data是字符串，可能直接就是ID
      else if (processedResult && processedResult.data && typeof processedResult.data === 'string' && processedResult.data.length > 0) {
        id = processedResult.data;
        console.log('[submitForm] 方法4成功获取ID:', id);
      }
      // 方法5：从data中的project对象获取（很多后端会将整个项目对象放在data中）
      else if (processedResult && processedResult.data && processedResult.data.project) {
        if (processedResult.data.project.id) {
          id = processedResult.data.project.id;
          console.log('[submitForm] 方法5a成功获取ID:', id);
        } else if (processedResult.data.project._id) {
          id = processedResult.data.project._id;
          console.log('[submitForm] 方法5b成功获取ID:', id);
        }
      }
      // 方法6：直接检查data对象中是否有任何可能看起来像ID的字段
      else if (processedResult && processedResult.data && typeof processedResult.data === 'object') {
        // 尝试常见的ID字段命名模式
        const possibleIdFields = ['_id', 'id', 'projectId', 'project_id', 'docId'];
        for (const field of possibleIdFields) {
          if (processedResult.data[field]) {
            id = processedResult.data[field];
            console.log(`[submitForm] 方法6成功从字段${field}获取ID:`, id);
            break;
          }
        }
      }
      // 方法7：如果处理过的result不行，尝试原始result对象
      else if (result && result !== processedResult) {
        console.log('[submitForm] 尝试从原始result中提取ID');
        // 从原始result直接获取
        if (result.id) {
          id = result.id;
          console.log('[submitForm] 方法7a成功获取ID:', id);
        }
        // 从原始result.data获取
        else if (result.data && typeof result.data === 'object') {
          if (result.data.id) {
            id = result.data.id;
            console.log('[submitForm] 方法7b成功获取ID:', id);
          } else if (result.data._id) {
            id = result.data._id;
            console.log('[submitForm] 方法7c成功获取ID:', id);
          }
        }
      }
      // 方法8：递归搜索整个返回对象（最强大的方法）
      if (!id) {
        const foundId = findIdInObject(result);
        if (foundId) {
          id = foundId;
          console.log('[submitForm] 方法8成功通过递归查找获取ID:', id);
        }
      }
      
      // 兜底：使用编辑页面已有ID
      if (!id && that.data.id) {
        id = that.data.id;
        console.log('[submitForm] 兜底方法使用已有ID:', id);
      }
      
      // 先重置提交状态
      that.setData({ isSubmitting: false });
      
      // 如果没有获取到ID，给出温和的提示并跳转到项目列表
      if (!id) {
        console.error('[submitForm] 无法获取项目ID!', processedResult);
        wx.showToast({
          title: '创建成功',
          icon: 'success',
          duration: 1500
        });
        
        // 延迟跳转到项目列表页面
        setTimeout(() => {
          wx.redirectTo({
            url: '../list/project_list',
            success: () => {
              console.log('[submitForm] 已跳转到项目列表页面');
            },
            fail: (err) => {
              console.error('跳转项目列表页失败:', err);
              wx.navigateBack();
            }
          });
        }, 1500);
        return;
      }
      
      // 尝试获取事件通道
      let eventChannel = that.getOpenerEventChannel();
      if (eventChannel && eventChannel.emit) {
        eventChannel.emit('refreshProjectList');
      }
      
      // 直接显示成功提示，然后在回调中跳转
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 1500,
        success: function() {
          // 延迟跳转，确保提示能够显示
          setTimeout(() => {
            wx.redirectTo({
              url: `../detail/project_detail?id=${id}`,
              success: () => {
                console.log('[submitForm] 成功跳转到项目详情页, id=', id);
              },
              fail: (err) => {
                console.error('跳转项目详情页失败:', err, '尝试返回列表页');
                wx.redirectTo({
                  url: '../list/project_list',
                  fail: (navErr) => {
                    console.error('返回列表页也失败:', navErr);
                    wx.navigateBack();
                  }
                });
              }
            });
          }, 1500);
        }
      });
    }).catch(err => {
      console.error('[submitForm] 提交失败：', err);
      
      // 显示更多错误细节
      console.error('[submitForm] 错误详情:', {
        message: err.message,
        code: err.code,
        stack: err.stack,
        detail: err.detail || '无详细信息'
      });
      
      // 尝试诊断错误原因
      let errorMessage = err.message || '提交失败，请重试';
      let errorTitle = '提交失败';
      
      // 检查是否是数据库连接问题
      if (errorMessage.includes('数据库') || 
          errorMessage.includes('collection') || 
          errorMessage.includes('database')) {
        errorTitle = '数据库错误';
        errorMessage = '无法连接到数据库或集合不存在。可能需要管理员创建相应的数据库集合。';
        
        // 尝试加载数据库检查工具
        try {
          const dbInspector = require('../../../config/debug/db_inspector');
          errorMessage += '\n\n请选择操作：';
          
          // 提供运行检查工具的选项
          wx.showModal({
            title: errorTitle,
            content: errorMessage,
            showCancel: true,
            cancelText: '关闭',
            confirmText: '检查数据库',
            success: (res) => {
              if (res.confirm) {
                // 提供检查或初始化选项
                wx.showActionSheet({
                  itemList: ['检查数据库', '初始化数据库'],
                  success: (actionRes) => {
                    if (actionRes.tapIndex === 0) {
                      // 运行数据库检查工具
                      dbInspector.checkDatabaseCollections().then(results => {
                        dbInspector.showCheckResults(results);
                        // 重置提交状态
                        that.setData({ isSubmitting: false });
                      }).catch(checkErr => {
                        pageHelper.showModal('检查失败', checkErr.message || '检查工具运行失败');
                        // 重置提交状态
                        that.setData({ isSubmitting: false });
                      });
                    } else if (actionRes.tapIndex === 1) {
                      // 运行数据库初始化工具
                      wx.showModal({
                        title: '确认初始化数据库',
                        content: '此操作将创建所需的数据库集合。确认继续吗？',
                        success: (confirmRes) => {
                          if (confirmRes.confirm) {
                            dbInspector.initDatabaseCollections().then(initResults => {
                              dbInspector.showInitResult(initResults);
                              
                              // 如果初始化成功，自动重试提交
                              if (initResults && initResults.code === 0) {
                                wx.showModal({
                                  title: '重新提交',
                                  content: '数据库初始化成功，是否立即重新提交项目？',
                                  success: (retryRes) => {
                                    if (retryRes.confirm && that._cachedFormData) {
                                      // 重新生成项目数据并提交
                                      const projectData = that._formDataToProject(that._cachedFormData);
                                      
                                      // 强制设置项目模块标识
                                      projectData.MODULE = 'plm';  
                                      projectData.PID = 'plm';    
                                      projectData.USE_PLM = true; 
                                      
                                      // 执行提交
                                      that._executeSubmit(projectData);
                                      return;
                                    } else {
                                      // 用户取消重试，重置提交状态
                                      that.setData({ isSubmitting: false });
                                    }
                                  }
                                });
                              } else {
                                // 初始化失败或用户取消，重置提交状态
                                that.setData({ isSubmitting: false });
                              }
                            }).catch(initErr => {
                              pageHelper.showModal('初始化失败', initErr.message || '初始化工具运行失败');
                              // 重置提交状态
                              that.setData({ isSubmitting: false });
                            });
                          } else {
                            // 用户取消初始化，重置提交状态
                            that.setData({ isSubmitting: false });
                          }
                        }
                      });
                    }
                  },
                  fail: () => {
                    // 操作取消，重置提交状态
                    that.setData({ isSubmitting: false });
                  }
                });
              } else {
                // 用户取消操作，重置提交状态
                that.setData({ isSubmitting: false });
              }
            }
          });
          return; // 提前返回，不显示普通错误对话框
        } catch (inspectorError) {
          console.error('[submitForm] 加载数据库检查工具失败:', inspectorError);
          // 继续显示普通错误对话框
        }
      } 
      // 检查权限问题
      else if (errorMessage.includes('权限') || 
              errorMessage.includes('permission') || 
              errorMessage.includes('access')) {
        errorTitle = '权限错误';
        errorMessage = '您可能没有创建项目的权限。请联系管理员。';
      }
      // 检查参数问题
      else if (errorMessage.includes('参数') || 
              errorMessage.includes('parameter') || 
              errorMessage.includes('field')) {
        errorTitle = '参数错误';
        errorMessage = '提交的数据格式不正确。请检查必填字段或联系管理员。';
      }
      
      wx.hideLoading();
      
      // 重置提交状态
      that.setData({ isSubmitting: false });
      
      pageHelper.showModal(errorTitle, errorMessage);
    });
  },
  
  /**
   * 项目类型变更（绑定WXML中的bindProjectTypeChange事件）
   */
  bindProjectTypeChange: function(e) {
    const index = parseInt(e.detail.value);
    const projectType = this.data.projectTypes[index];
    const projectTypeName = this.data.projectTypeNames[projectType] || '其他类型';
    
    console.log('====== 项目类型变更 ======');
    console.log('选择索引:', index);
    console.log('选择项目类型:', projectType);
    console.log('项目类型名称:', projectTypeName);
    
    // 更新项目类型和类型名称
    this.setData({
      'projectTypeIndex': index,
      'project.projectType': projectType,  // 保存字符串值，不是索引
      'project.projectTypeName': projectTypeName,
      'formData.projectType': projectType, // 保存字符串值，不是索引
      'formData.projectTypeName': projectTypeName
    });
    
    console.log('====== 项目类型更新后 ======');
    console.log('当前项目类型:', this.data.project.projectType);
    console.log('表单项目类型:', this.data.formData.projectType);
    
    // 不同类型项目可能有不同的表单配置
    this.initFormConfig(projectType);
  },
  
  /**
   * 负责人选择变更
   */
  bindLeaderChange: function(e) {
    const index = parseInt(e.detail.value);
    const leader = this.data.leaders[index];
    
    console.log('====== 项目负责人变更 ======');
    console.log('选择索引:', index);
    console.log('选择负责人:', leader);
    
    this.setData({
      'leaderIndex': index,
      'project.projectLeadId': leader.id,
      'project.projectLead': leader.name,
      'formData.projectLeadId': leader.id,
      'formData.projectLead': leader.name
    });
    
    console.log('====== 项目负责人更新后 ======');
    console.log('负责人ID:', this.data.project.projectLeadId);
    console.log('负责人名称:', this.data.project.projectLead);
  },
  
  /**
   * 部门选择变更
   */
  bindDepartmentChange: function(e) {
    const index = parseInt(e.detail.value);
    const department = this.data.departments[index];
    
    console.log('====== 部门变更 ======');
    console.log('选择索引:', index);
    console.log('选择部门:', department);
    
    this.setData({
      'departmentIndex': index,
      'project.department': department,
      'formData.department': department
    });
    
    console.log('====== 部门更新后 ======');
    console.log('当前部门:', this.data.project.department);
  },
  
  /**
   * 销售人员选择变更
   */
  bindSalespersonChange: function(e) {
    const index = parseInt(e.detail.value);
    const salesperson = this.data.salespeople[index];
    
    console.log('====== 销售人员变更 ======');
    console.log('选择索引:', index);
    console.log('选择销售:', salesperson);
    
    this.setData({
      'salespersonIndex': index,
      'project.salespersonId': salesperson.id,
      'project.salespersonName': salesperson.name,
      'formData.salespersonId': salesperson.id,
      'formData.salespersonName': salesperson.name
    });
    
    console.log('====== 销售人员更新后 ======');
    console.log('销售ID:', this.data.project.salespersonId);
    console.log('销售名称:', this.data.project.salespersonName);
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log('======== 页面卸载 ========');
    
    // 销毁MobX绑定
    if (this.storeBindings) {
      try {
        this.storeBindings.destroyStoreBindings();
        console.log('成功销毁MobX绑定');
      } catch (e) {
        console.error('销毁MobX绑定出错:', e);
      }
    }
    
    // 清理项目数据 - 尝试多种方式确保清理成功
    console.log('开始清理项目数据...');
    
    // 方式1：使用页面中已导入的projectStore
    try {
      console.log('尝试方式1: 使用页面中导入的projectStore');
      if (projectStore && typeof projectStore.clearProject === 'function') {
        projectStore.clearProject();
        console.log('方式1清理成功');
      } else {
        console.warn('方式1无法使用: projectStore或clearProject不存在');
      }
    } catch (e) {
      console.error('方式1清理失败:', e);
    }
    
    // 方式2：使用配置中的projectStore
    try {
      console.log('尝试方式2: 使用配置中的projectStore');
      if (this.configProjectStore && typeof this.configProjectStore.clearProject === 'function') {
        this.configProjectStore.clearProject();
        console.log('方式2清理成功');
      } else {
        console.warn('方式2无法使用: configProjectStore或clearProject不存在');
      }
    } catch (e) {
      console.error('方式2清理失败:', e);
    }
    
    // 方式3：最后兜底，手动清理数据
    try {
      console.log('尝试方式3: 手动清理');
      // 这是一个兜底操作，直接修改全局变量(不推荐但可作为最后手段)
      if (getApp() && getApp().globalData && getApp().globalData.currentProject) {
        getApp().globalData.currentProject = null;
        console.log('方式3清理成功');
      } else {
        console.warn('方式3无法使用: 全局变量不存在');
      }
    } catch (e) {
      console.error('方式3清理失败:', e);
    }
    
    console.log('项目数据清理完成');
  },

  // 客户名称输入
  bindCustomerNameInput: function(e) {
    this.setData({
      'project.customerName': e.detail.value,
      'formData.customerName': e.detail.value
    });
  },

  // 项目型号名称输入
  bindModelInput: function(e) {
    this.setData({
      'project.model': e.detail.value,
      'formData.model': e.detail.value
    });
  },

  // 有无样机选择
  bindHasSampleChange: function(e) {
    const hasSample = ['有', '无'][parseInt(e.detail.value)];
    
    // 当选择"有样机"时，确保初始化sampleImages为空数组
    const updates = {
      'project.hasSample': hasSample,
      'formData.hasSample': hasSample
    };
    
    // 确保sampleImages已初始化为空数组
    if (hasSample === '有' && !this.data.project.sampleImages) {
      updates['project.sampleImages'] = [];
      updates['formData.sampleImages'] = [];
    }
    
    this.setData(updates);
  },

  // 选择样机图片
  chooseSampleImage: function() {
    const that = this;
    wx.chooseImage({
      count: 9 - (that.data.project.sampleImages ? that.data.project.sampleImages.length : 0),
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        // 合并现有图片和新选择的图片
        const sampleImages = that.data.project.sampleImages || [];
        const newImages = sampleImages.concat(res.tempFilePaths);
        
        that.setData({
          'project.sampleImages': newImages,
          'formData.sampleImages': newImages
        });
      }
    });
  },

  // 预览图片
  previewImage: function(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: this.data.project.sampleImages
    });
  },

  // 删除样机图片
  deleteSampleImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const sampleImages = this.data.project.sampleImages;
    sampleImages.splice(index, 1);
    
    this.setData({
      'project.sampleImages': sampleImages,
      'formData.sampleImages': sampleImages
    });
  },

  // 样品需求量输入
  bindSampleCountInput: function(e) {
    this.setData({
      'project.sampleCount': e.detail.value,
      'formData.sampleCount': e.detail.value
    });
  },

  // 开始时间选择器事件
  bindStartDateChange: function(e) {
    this.setData({
      'project.startDate': e.detail.value,
      'formData.startDate': e.detail.value
    });
  },

  // 截止时间选择器事件
  bindDeadlineChange: function(e) {
    this.setData({
      'project.deadline': e.detail.value,
      'formData.deadline': e.detail.value
    });
  },

  // 取消操作
  cancel: function() {
    wx.showModal({
      title: '确认取消',
      content: '确定要放弃当前编辑内容吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateBack();
        }
      }
    });
  },

  // 项目描述输入
  bindDescriptionInput: function(e) {
    this.setData({
      'project.description': e.detail.value,
      'formData.description': e.detail.value
    });
  },

  // 选择附件
  chooseAttachment() {
    let that = this;
    wx.chooseMessageFile({
      count: 5,
      type: 'file',
      success(res) {
        const tempFiles = res.tempFiles;
        console.log('选择的附件:', tempFiles);
        
        // 显示上传中提示
        wx.showLoading({
          title: '上传附件中...',
          mask: true
        });
        
        // 上传附件到云存储
        that._uploadAttachments(tempFiles);
      }
    });
  },
  
  /**
   * 上传附件到云存储
   * @param {Array} tempFiles 临时文件数组
   */
  _uploadAttachments(tempFiles) {
    const promises = tempFiles.map(file => {
      return new Promise((resolve, reject) => {
        const cloudPath = `project_attachments/${Date.now()}_${Math.floor(Math.random()*1000)}_${file.name}`;
        
        wx.cloud.uploadFile({
          cloudPath,
          filePath: file.path,
          success: res => {
            console.log('附件上传成功:', res);
            resolve({
              name: file.name,
              fileID: res.fileID,
              size: file.size,
              type: file.type,
              uploadTime: Date.now()
            });
          },
          fail: err => {
            console.error('附件上传失败:', err);
            reject(err);
          }
        });
      });
    });
    
    Promise.all(promises).then(attachments => {
      // 合并现有附件和新上传的附件
      const newAttachments = [...this.data.attachments, ...attachments];
      
      this.setData({
        attachments: newAttachments,
        'project.attachments': newAttachments
      });
      
      wx.hideLoading();
      wx.showToast({
        title: '附件上传成功',
        icon: 'success'
      });
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '附件上传失败',
        icon: 'none'
      });
      console.error('附件上传失败:', err);
    });
  },
  
  /**
   * 删除附件
   * @param {Object} e 事件对象
   */
  deleteAttachment(e) {
    const index = e.currentTarget.dataset.index;
    const attachments = [...this.data.attachments];
    
    const deletedFile = attachments.splice(index, 1)[0];
    
    // 同时更新data中的attachments和project.attachments
    this.setData({
      attachments: attachments,
      'project.attachments': attachments
    });
    
    // 从云存储中删除文件
    if (deletedFile && deletedFile.fileID) {
      wx.cloud.deleteFile({
        fileList: [deletedFile.fileID],
        success: res => {
          console.log('云存储文件删除成功:', res);
        },
        fail: err => {
          console.error('云存储文件删除失败:', err);
        }
      });
    }
  },
  
  /**
   * 预览附件
   * @param {Object} e 事件对象
   */
  previewAttachment(e) {
    const index = e.currentTarget.dataset.index;
    const file = this.data.attachments[index];
    
    if (!file || !file.fileID) return;
    
    wx.showLoading({
      title: '打开文件中...',
      mask: true
    });
    
    // 获取真实链接并打开
    wx.cloud.getTempFileURL({
      fileList: [file.fileID],
      success: res => {
        wx.hideLoading();
        const tempUrl = res.fileList[0].tempFileURL;
        
        wx.openDocument({
          filePath: tempUrl,
          showMenu: true,
          success: function() {
            console.log('打开文件成功');
          },
          fail: function(err) {
            console.error('打开文件失败:', err);
            wx.showToast({
              title: '无法预览该类型文件',
              icon: 'none'
            });
          }
        });
      },
      fail: err => {
        wx.hideLoading();
        console.error('获取临时链接失败:', err);
        wx.showToast({
          title: '获取文件链接失败',
          icon: 'none'
        });
      }
    });
  },
  
  /**
   * 控制模式选择器变化事件
   */
  bindControlModeChange: function(e) {
    const index = e.detail.value;
    this.setData({
      ['project.controlMode']: this.data.controlModes[index],
      ['formData.controlMode']: this.data.controlModes[index]
    });
  },

  /**
   * 防护涂层选择器变化事件
   */
  bindConformalCoatingChange: function(e) {
    const value = e.detail.value === '0' ? '有' : '无';
    this.setData({
      ['project.conformalCoating']: value,
      ['formData.conformalCoating']: value
    });
  },

  /**
   * 最大功率输入事件
   */
  bindMaxPowerInput: function(e) {
    this.setData({
      ['project.maxPower']: e.detail.value,
      ['formData.maxPower']: e.detail.value
    });
  },

  /**
   * 额定电压输入事件
   */
  bindRatedVoltageInput: function(e) {
    this.setData({
      ['project.ratedVoltage']: e.detail.value,
      ['formData.ratedVoltage']: e.detail.value
    });
  },

  /**
   * 最大转速输入事件
   */
  bindMaxSpeedInput: function(e) {
    this.setData({
      ['project.maxSpeed']: e.detail.value,
      ['formData.maxSpeed']: e.detail.value
    });
  },

  /**
   * 极对数输入事件
   */
  bindPolePairsInput: function(e) {
    this.setData({
      ['project.polePairs']: e.detail.value,
      ['formData.polePairs']: e.detail.value
    });
  },

  /**
   * 霍尔传感器选择器变化事件
   */
  bindHasHallChange: function(e) {
    const value = ['有', '无'][e.detail.value];
    this.setData({
      ['project.hasHall']: value,
      ['formData.hasHall']: value
    });
  },

  /**
   * FG信号选择器变化事件
   */
  bindHasFGChange: function(e) {
    const value = ['有', '无'][e.detail.value];
    this.setData({
      ['project.hasFG']: value,
      ['formData.hasFG']: value
    });
  },

  /**
   * 控制算法选择器变化事件
   */
  bindControlAlgorithmChange: function(e) {
    const index = e.detail.value;
    this.setData({
      ['project.controlAlgorithm']: this.data.controlAlgorithms[index],
      ['formData.controlAlgorithm']: this.data.controlAlgorithms[index]
    });
  },

  /**
   * 旋转方向选择器变化事件
   */
  bindRotationChange: function(e) {
    const index = e.detail.value;
    this.setData({
      ['project.rotation']: this.data.rotationOptions[index],
      ['formData.rotation']: this.data.rotationOptions[index]
    });
  },

  /**
   * 制动功能选择器变化事件
   */
  bindHasBrakeChange: function(e) {
    const value = e.detail.value === '0' ? '有' : '无';
    this.setData({
      ['project.hasBrake']: value,
      ['formData.hasBrake']: value
    });
  },

  /**
   * 工作温度输入事件
   */
  bindWorkTempInput: function(e) {
    this.setData({
      ['project.workTemp']: e.detail.value,
      ['formData.workTemp']: e.detail.value
    });
  },

  /**
   * 认证要求输入事件
   */
  bindCertificationInput: function(e) {
    this.setData({
      ['project.certification']: e.detail.value,
      ['formData.certification']: e.detail.value
    });
  },

  /**
   * 低功耗输入事件
   */
  bindLowPowerInput: function(e) {
    this.setData({
      ['project.lowPower']: e.detail.value,
      ['formData.lowPower']: e.detail.value
    });
  },

  /**
   * 启动时间输入事件
   */
  bindStartupTimeInput: function(e) {
    this.setData({
      ['project.startupTime']: e.detail.value,
      ['formData.startupTime']: e.detail.value
    });
  },

  // 堵转保护参数输入事件
  bindStallHoldTimeInput: function(e) {
    this.setData({
      ['project.stallHoldTime']: e.detail.value,
      ['formData.stallHoldTime']: e.detail.value
    });
  },

  bindStallRestartTimeInput: function(e) {
    this.setData({
      ['project.stallRestartTime']: e.detail.value,
      ['formData.stallRestartTime']: e.detail.value
    });
  },

  bindStallRestartCountInput: function(e) {
    this.setData({
      ['project.stallRestartCount']: e.detail.value,
      ['formData.stallRestartCount']: e.detail.value
    });
  },

  // 过压保护参数输入事件
  bindOvervoltageValueInput: function(e) {
    this.setData({
      ['project.overvoltageValue']: e.detail.value,
      ['formData.overvoltageValue']: e.detail.value
    });
  },

  bindOvervoltageRecoveryValueInput: function(e) {
    this.setData({
      ['project.overvoltageRecoveryValue']: e.detail.value,
      ['formData.overvoltageRecoveryValue']: e.detail.value
    });
  },

  // 欠压保护参数输入事件
  bindUndervoltageValueInput: function(e) {
    this.setData({
      ['project.undervoltageValue']: e.detail.value,
      ['formData.undervoltageValue']: e.detail.value
    });
  },

  bindUndervoltageRecoveryValueInput: function(e) {
    this.setData({
      ['project.undervoltageRecoveryValue']: e.detail.value,
      ['formData.undervoltageRecoveryValue']: e.detail.value
    });
  },

  // 温度保护参数输入事件
  bindProtectionTempInput: function(e) {
    this.setData({
      ['project.protectionTemp']: e.detail.value,
      ['formData.protectionTemp']: e.detail.value
    });
  },

  bindRecoveryTempInput: function(e) {
    this.setData({
      ['project.recoveryTemp']: e.detail.value,
      ['formData.recoveryTemp']: e.detail.value
    });
  },

  // 过流保护参数输入事件
  bindOvercurrentValueInput: function(e) {
    this.setData({
      ['project.overcurrentValue']: e.detail.value,
      ['formData.overcurrentValue']: e.detail.value
    });
  },

  // 限流保护参数输入事件
  bindCurrentLimitValueInput: function(e) {
    this.setData({
      ['project.currentLimitValue']: e.detail.value,
      ['formData.currentLimitValue']: e.detail.value
    });
  },

  // 堵孔保护参数输入事件
  bindBlockageDiameterInput: function(e) {
    this.setData({
      ['project.blockageDiameter']: e.detail.value,
      ['formData.blockageDiameter']: e.detail.value
    });
  },

  /**
   * 控制详细描述输入事件
   */
  bindControlDescriptionInput: function(e) {
    this.setData({
      'project.controlDescription': e.detail.value,
      'formData.controlDescription': e.detail.value
    });
  },

  // 通用表单项变更处理器
  bindFormItemChange: function(e) {
    const { field, type } = e.currentTarget.dataset;
    let value = e.detail.value;
    
    // 根据不同表单控件类型处理值
    if (type === 'select') {
      const options = e.currentTarget.dataset.options.split(',');
      value = options[value];
    }
    
    this.setData({
      [`project.${field}`]: value
    });
  },

  // 控制方式选择
  bindControlInterfaceChange: function(e) {
    const interfaces = ['按键控制', 'PWM控制', 'CLOCK控制', 'VSP控制', 'IIC协议控制', 'UART控制', 'SPI控制'];
    const selectedInterface = interfaces[e.detail.value];
    
    let data = {
      ['project.controlInterface']: selectedInterface
    };

    // 设置PWM控制默认参数
    if (selectedInterface === 'PWM控制') {
      data = {
        ...data,
        ['project.pwmStartDuty']: '10',      // 开机点占空比：10%
        ['project.pwmStopDuty']: '8',        // 关机点占空比：8%
        ['project.pwmDutyRange']: '10～90',   // 有效占空比：10%~90%
        ['project.pwmFreqRange']: '1～10'    // 频率范围：1~10 Hz
      };
    }
    
    // 设置VSP控制默认参数
    if (selectedInterface === 'VSP控制') {
      data = {
        ...data,
        ['project.vspStartVoltage']: '1.0',    // 开机点电压：1.0V
        ['project.vspStopVoltage']: '0.8',   // 关机点电压：0.8V
        ['project.vspVoltageRange']: '1.0～4.5' // 有效电压范围：1.0~4.5V
      };
    }

    this.setData(data);
  },

  // PWM控制参数输入
  bindPwmStartDutyInput: function(e) {
    this.setData({
      'project.pwmStartDuty': e.detail.value,
      'formData.pwmStartDuty': e.detail.value
    });
  },

  bindPwmStopDutyInput: function(e) {
    this.setData({
      'project.pwmStopDuty': e.detail.value,
      'formData.pwmStopDuty': e.detail.value
    });
  },

  bindPwmDutyRangeInput: function(e) {
    this.setData({
      'project.pwmDutyRange': e.detail.value,
      'formData.pwmDutyRange': e.detail.value
    });
  },

  bindPwmFreqRangeInput: function(e) {
    this.setData({
      'project.pwmFreqRange': e.detail.value,
      'formData.pwmFreqRange': e.detail.value
    });
  },

  // VSP控制参数输入
  bindVspStartVoltageInput: function(e) {
    this.setData({
      'project.vspStartVoltage': e.detail.value,
      'formData.vspStartVoltage': e.detail.value
    });
  },

  bindVspStopVoltageInput: function(e) {
    this.setData({
      'project.vspStopVoltage': e.detail.value,
      'formData.vspStopVoltage': e.detail.value
    });
  },

  bindVspVoltageRangeInput: function(e) {
    this.setData({
      'project.vspVoltageRange': e.detail.value,
      'formData.vspVoltageRange': e.detail.value
    });
  },

  /**
   * 堵转保护选择变更处理函数
   */
  bindStallProtectionChange: function(e) {
    const value = this.data.protectionOptions[e.detail.value];
    this.setData({
      'project.stallProtection': value,
      'formData.stallProtection': value
    });
  },

  /**
   * 过压保护选择变更处理函数
   */
  bindOvervoltageProtectionChange: function(e) {
    const value = this.data.protectionOptions[e.detail.value];
    this.setData({
      'project.overvoltageProtection': value,
      'formData.overvoltageProtection': value
    });
  },
  
  /**
   * 欠压保护选择变更处理函数
   */
  bindUndervoltageProtectionChange: function(e) {
    const value = this.data.protectionOptions[e.detail.value];
    this.setData({
      'project.undervoltageProtection': value,
      'formData.undervoltageProtection': value
    });
  },
  
  /**
   * 温度保护选择变更处理函数
   */
  bindTemperatureProtectionChange: function(e) {
    const value = this.data.protectionOptions[e.detail.value];
    this.setData({
      'project.temperatureProtection': value,
      'formData.temperatureProtection': value
    });
  },
  
  /**
   * 过流保护选择变更处理函数
   */
  bindOvercurrentProtectionChange: function(e) {
    const value = this.data.protectionOptions[e.detail.value];
    this.setData({
      'project.overcurrentProtection': value,
      'formData.overcurrentProtection': value
    });
  },
  
  /**
   * 限流保护选择变更处理函数
   */
  bindCurrentLimitProtectionChange: function(e) {
    const value = this.data.currentLimitOptions[e.detail.value];
    this.setData({
      'project.currentLimitProtection': value,
      'formData.currentLimitProtection': value
    });
  },
  
  /**
   * 堵孔保护选择变更处理函数
   */
  bindBlockageProtectionChange: function(e) {
    const value = this.data.protectionOptions[e.detail.value];
    this.setData({
      'project.blockageProtection': value,
      'formData.blockageProtection': value
    });
  },
  
  /**
   * 缺相保护选择变更处理函数
   */
  bindPhaseProtectionChange: function(e) {
    const value = this.data.protectionOptions[e.detail.value];
    this.setData({
      'project.phaseProtection': value,
      'formData.phaseProtection': value
    });
  },
}); 